﻿package base.mvc.section {
	import base.Singleton;
	import flash.events.EventDispatcher;
	import swfAddress.SWFAddress;
	import swfAddress.SWFAddressEvent;
	import com.google.analytics.GATracker;

	public class ModelSection extends Singleton {
		
		private static var modelDispatcher: EventDispatcher = new EventDispatcher();
		
		private static var _parameters: Object	= {}
		public static var gaTracker: GATracker;
		
		internal static function init(): void {
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, ModelSection.handleSWFAddress);
		}
		
		public static function addEventListener(type: String, func: Function, priority: int = 0): void {
			ModelSection.modelDispatcher.addEventListener(type, func, false, priority);
		}
	
		public static function removeEventListener(type: String, func: Function): void {
			ModelSection.modelDispatcher.removeEventListener(type, func);
		}
		
		public static function dispatchEvent(type: String, data: * = null): void {
			ModelSection.modelDispatcher.dispatchEvent(new EventModelSection(type, data));
		}
		
		public static function set indSection(value: Object): void {
			if (value != ViewSectionManager.currIndSection) ModelSection.dispatchEvent(EventModelSection.START_CHANGE_SECTION, {oldIndSection: ViewSectionManager.currIndSection, newIndSection: value}); 
		}
		
		public static function get parameters(): Object { 
			return ModelSection._parameters;
		}
		
		private static function handleSWFAddress(e: SWFAddressEvent): void {
			ModelSection._parameters = SWFAddress.getParametersObject();
			var currentSwfAddress: String = SWFAddress.getPath();
			if (ModelSection.gaTracker) ModelSection.gaTracker.trackPageview(SWFAddress.getValue());
			if ((currentSwfAddress == "") || (currentSwfAddress == "/")) SWFAddress.setValue(ViewSectionManager.startIndSection);
			else ModelSection.indSection = ViewSectionManager.joinIndSectionFromArrElement(ViewSectionManager.splitIndSectionFromStr(currentSwfAddress));
			//if ((currentSwfAddress != "") && (currentSwfAddress != "/")) ModelSection.indSection = ViewSectionManager.joinIndSectionFromArrElement(ViewSectionManager.splitIndSectionFromStr(currentSwfAddress));
			ModelSection.dispatchEvent(EventModelSection.PARAMETERS_CHANGE);
		}
		
	}

}